from django.conf import settings
from rest_framework.viewsets import ModelViewSet
from meiduo_admin.my_paginate import MyPageNumberPagination
from goods.models import SPU, Brand, GoodsCategory, SKUImage
from meiduo_admin.serializer import spu_serializer
from rest_framework.response import Response
from fdfs_client.client import Fdfs_client

from meiduo_mall.utils.MyStorage import MyStorage


class SPUView(ModelViewSet):
    pagination_class = MyPageNumberPagination
    queryset = SPU.objects.all()
    serializer_class = spu_serializer.SPUSerializer

    def brand(self, request):
        brands = Brand.objects.all()

        serializer = spu_serializer.BrandSerializer(instance=brands, many=True)

        return Response(serializer.data)


    def category(self, request):
        category1 = GoodsCategory.objects.filter(parent__id=None)
        serializer = spu_serializer.CategorySerializer(instance=category1, many=True)
        return Response(serializer.data)

    def category_sub(self, request, pk):
        categories = GoodsCategory.objects.filter(parent__id=pk)
        serializer = spu_serializer.CategorySerializer(instance=categories, many=True)
        return Response(serializer.data)


    def upload_image(self, request):
        # 1,获取参数
        image = request.FILES.get("image")

        # 2,上传图片,判断是否上传成功
        image_url = MyStorage().save(None, image)
        if not image_url:
            return Response({"errmsg": "上传失败"}, status=400)

        # 3,返回响应
        return Response({
            "img_url": settings.BASE_URL + image_url
        })

